package com.thread.lock;

/**
 * Created by Sunny on 2016/4/14.
 */
public class DeadlockTest1 {
    public static void main(String[] args) {
        try {
            Service s1 = new Service();
            s1.setUsername("a");
            Thread d1 = new Thread(s1);
            d1.setName("SunnyThread1");
            d1.start();
            Thread.sleep(100);
            Service s2 = new Service();
            s2.setUsername("b");
            Thread d2 = new Thread(s2);
            d2.setName("SunnyThread2");
            d2.start();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }


    }
}

class Service implements  Runnable {

    public String username;
    public Object lock1 = new Object();
    public Object lock2 = new Object();

    public void setUsername(String username){
        this.username = username;
    }

    public void run() {
        if("a".equals(username)){
            synchronized (lock1){
                try {
                    System.out.println("username="+username);
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            synchronized (lock2){
                System.out.println("lock1 -> lock2");
            }
        }
        if("b".equals(username)){
            synchronized (lock2){
                try {
                    System.out.println("username="+username);
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            synchronized (lock1){
                System.out.println("lock2 -> lock1");
            }
        }
    }
}